package com.tnl.web.controller;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Employer;
import com.tnl.web.config.controller.Authentication;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.service.SMSService;
import com.tnl.web.util.qualifiers.AuditIt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class EmployerController {

	private static final Logger logger = LoggerFactory
			.getLogger(EmployerController.class);

	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private TempCompanyDAO tempCompanyDAO;
	@Autowired
	private EmployerDAO empDAO;
	
	@Autowired
	private Authentication authentication;

	@Autowired
	private SMSService smsService;
	
	// HR管理首页
	@AuditIt(module = "HR", action = "hr_view", description = "show the hr index page")
	@RequestMapping(value = "admin/hr/manage.page", method = RequestMethod.GET)
	public String toList(HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {

			logger.info("empty userid ,wexin browser is needed.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}

		List<Company> companies =  companyDAO.getALL();
		model.addAttribute("companies", companies);
		return "admin/employer/hrlist";
	}
	
	// 显示编辑表单页面
	@AuditIt(module = "HR", action = "editHr", description = "show the hr edit page")
	@RequestMapping(value = "admin/hr/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String hrid = request.getParameter("hrid");
		Employer employer = null;
		if (StringUtils.hasText(hrid)) {
			employer = empDAO.getById(Integer.parseInt(hrid));
			model.addAttribute("hr", employer);
		} else {
			return "admin/errorpage";
		}

		return "admin/employer/hreditform";
	}

	// 显示HR详细信息页面
	@RequestMapping(value = "admin/hr/detail.page", method = RequestMethod.GET)
	public String employerDetail(HttpServletRequest request, Model model) {

		String hrid = request.getParameter("hrid");
		
		Employer employer = null;
		if (StringUtils.hasText(hrid)) {
			employer = empDAO.getById(Integer.parseInt(hrid));
			model.addAttribute("hr", employer);
		} else {
			return "admin/errorpage";
		}
		
		int companyid = employer.getCompanyId();
		
		Company company = null;
		if(employer.getBinded() == 1) {
			company = companyDAO.getById(companyid);
		} else {
			company = tempCompanyDAO.getById(companyid);
		}
		model.addAttribute("company", company);
		
		return "admin/employer/hrdetail";
	}
	
	@AuditIt(module = "Company", action = "approveCompany", description = "show the hr edit page")
	@RequestMapping(value = "admin/hr/approve.page", method = RequestMethod.GET)
	public String toBindPage(HttpServletRequest request, Model model) {

		String hrid = request.getParameter("hrid");
		Employer employer = null;
		if (StringUtils.hasText(hrid)) {
			employer = empDAO.getById(Integer.parseInt(hrid));
			model.addAttribute("hr", employer);
		} else {
			return "admin/errorpage";
		}
		
		int companyId = employer.getCompanyId();
		Company company = null;
		if (companyId >0) {
			company = companyDAO.getById(companyId);
			model.addAttribute("company", company);
		} else {
			return "admin/errorpage";
		}

		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);

		return "admin/employer/hrbound";
	}
	
	// 搜索数据
	@RequestMapping(value = "admin/hr/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Employer> searchHr(jqGridRequestObject request, 
			String sname, Integer scompanyid, String sphone) {
		
		jqGridResponseObject<Employer> msg = new jqGridResponseObject<Employer>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = empDAO.getCountOfAll(sname,scompanyid,sphone);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		List<Employer> list = empDAO.getAllWithLimit(sname,scompanyid,sphone,start, pagesize);
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 更新数据
	@AuditIt(module = "HR", action = "editHr", description = "update hr action")
	@RequestMapping(value = "admin/hr/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateEmployer(HttpServletRequest request,  Employer employer) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if(employer == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		if(employer.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		
		Employer ep = empDAO.getById(employer.getId());
		if(ep == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该HR");
			return msg;
		}
		
		ep.setName(employer.getName());
		ep.setTelephone(employer.getTelephone());
		ep.setPhone(employer.getPhone());
		ep.setEmail(employer.getEmail());

		int result = empDAO.update(ep);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}
	
	// 删除数据
	@AuditIt(module = "HR", action = "deleteHr", description = "delete hr action")
	@RequestMapping(value = "admin/hr/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteEmployer(HttpServletRequest request, Integer hrid) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if (hrid == null) {
			logger.debug("empid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}
		
		int result = empDAO.delete(String.valueOf(hrid));
		if (result == 1) {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
			return msg;
		}

		msg.setErrorcode("50001");
		msg.setMsg("删除失败");
		return msg;
	}
	
	// 更新数据
	@AuditIt(module = "Company", action = "approveCompany", description = "update hr action")
	@RequestMapping(value = "admin/hr/approve.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg approveEmployer(HttpServletRequest request,  Company company) {
		
		ErrorMsg msg = new ErrorMsg();
		
		String hrid = request.getParameter("hrid");
		Employer employer = null;
		if (StringUtils.hasText(hrid)) {
			employer = empDAO.getById(Integer.parseInt(hrid));
		} else {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		
		if(employer == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		if(employer.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		
		Employer ep = empDAO.getById(employer.getId());
		if(ep == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该HR");
			return msg;
		}
		
		if(company == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定HR信息");
			return msg;
		}
		
		String companyName = company.getName();
		Company cp = companyDAO.getByName(companyName);
		
		if(cp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("操作出错");
			return msg;
		}
		
		ep.setCompanyId(cp.getId());
		ep.setCompanyName(cp.getName());
		ep.setBinded(1);//认证标志

		int result = empDAO.update(ep);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}
		// 通知HR审核成功
		String text = "您的账号已通过审核，您可至公众号【headoffer会猎】“公司HR”-“发布职位”菜单免费发布职位啦！";
		SMSService.sendSMS(ep.getPhone(),text);
		logger.info("HR ["+ep.getPhone()+"] 认证短信发送成功！");

		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}

	/*
	@RequestMapping(value = "admin/hr/toView.page", method = RequestMethod.GET)
	public String toView(HttpServletRequest request, int id, Model model) {
		Employer emp = empDAO.getById(id);
		model.addAttribute("employer", emp);
		return "admin/hr/detail";
	}
	
	@RequestMapping(value = "admin/hr/toEdit.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, int id, Model model) {
		Employer emp = empDAO.getById(id);
		model.addAttribute("employer", emp);
		return "admin/hr/edit";
	}
	
	@RequestMapping(value = "admin/hr/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createEmployer(Employer emp) {
		Date now= new Date();
		ErrorMsg msg = new ErrorMsg();
		boolean exist = isExist(emp);
		
		emp.setCreateDate(now.getTime());
		emp.setActive(1);//change the enum value
		int result = empDAO.save(emp);
		  if(result == -1 )
		    {
		    	msg.setErrorcode("50001");
				msg.setMsg("can not save the person" + emp.getName());
				return msg;
		    }
			msg.setErrorcode("0");
			msg.setMsg("success");
			
			return msg;
	}
	//@RequestMapping(value = "admin/candidate/checkExist.do", method = RequestMethod.POST)
		private boolean isExist(Employer employer) {
			if (employer == null) {
				return true;
			}

			if (StringUtils.hasText(employer.getPhone())) {
				Person persondb = empDAO.getByPhone(employer.getPhone());
				if (persondb == null) {
					return false;
				}
			}
			return true;
		}
	@RequestMapping(value = "admin/hr/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateEmployer(HttpServletRequest request,Employer emp, Model model) {
		ErrorMsg msg = new ErrorMsg();
		int result = empDAO.update(emp);
		  if(result == -1 )
		    {
		    	msg.setErrorcode("50001");
				msg.setMsg("can not save the employer" + emp.getName());
				return msg;
		    }
			msg.setErrorcode("0");
			msg.setMsg("success");
			
			return msg;
	}
	
	@RequestMapping(value = "admin/hr/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteEmployer(HttpServletRequest request, String id, Model model) {
		ErrorMsg msg = new ErrorMsg();
		int result = empDAO.delete(id);
		  if(result == -1 )
		    {
		    	msg.setErrorcode("50001");
				msg.setMsg("can not save the employer " + id);
				return msg;
		    }
			msg.setErrorcode("0");
			msg.setMsg("success");
			
			return msg;
	}
	hr/approve.do
	@RequestMapping(value = "admin/hr/activate.do", method = RequestMethod.GET)
	public String activateEmployer(HttpServletRequest request, int id, Model model) {
		
		Employer emp = empDAO.getById(id);
		if (emp!=null)
		{
			emp.setActive(1);//change the enum value
			int result = empDAO.update(emp);
		}
	
		return "admin/hr/list";
	}
	
	@RequestMapping(value = "admin/hr/inactivate.do", method = RequestMethod.GET)
	public String inactivateEmployer(HttpServletRequest request, int id, Model model) {
		Employer emp = empDAO.getById(id);
		if (emp!=null)
		{
			emp.setActive(0);//change the enum value
			int result = empDAO.update(emp);
		}
		return "admin/hr/list";
	}
	*/
	

}
